package org.apache.ofbiz.base.start;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.ofbiz.base.util.UtilValidate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StartForJar {

	private final static Logger logger = LoggerFactory.getLogger(StartForJar.class);
	private static final String fromUrl = "bosentHome";
	private static final String toUrl = "runtime";
	
	public static void start() {
		//System.out.println("start ofbiz for jar ...... " + (new File(".")).getAbsolutePath());
		setBosentHome();
		Start.start();
	}
	
	public static void main(String[] args) {
		//System.out.println("start ofbiz for jar ...... " + (new File(".")).getAbsolutePath());
		String resource;
		if(args != null) { 
			String[] resources = args;
			int ideUrl = args.length;
			for(int arg2 = 0; arg2 < ideUrl; ++arg2) { 
				resource = resources[arg2];
				System.out.println("[" + resource + "]");
			}
		}
		setBosentHome();
		Start.main(args);
	}

	public static void setBosentHome() {
		/*File directory = new File("");// 参数为空
        String courseFile;
		try {
			courseFile = directory.getCanonicalPath();
			System.out.println("path2:"+courseFile);
		} catch (IOException e) {
			e.printStackTrace();
		}*/
        String runtimeDir = System.getProperty("user.dir");
        String startFile = "start.properties";
		File propsFile = new File(runtimeDir+"/runtime/bosentHome/framework/" + startFile);
		if (!propsFile.exists()) {
			throw new IllegalArgumentException("cant not found " + startFile);
		}
//		System.out.println("path4:" +System.getProperty("user.dir"));
		//System.out.println("path5:"+System.getProperty("java.class.path").split(";")[0]);
		/*String theFileName = "start.properties";
		File propsFile = new File(theFileName);
		if (!propsFile.exists()) {
			propsFile = new File("./runtime/bosentHome/framework/" + theFileName);
			if (!propsFile.exists()) {
				propsFile = new File("./framework-config/" + theFileName);
				if (!propsFile.exists()) {
					throw new IllegalArgumentException("can\'t find " + theFileName);
				}
			}
		}*/
		logger.info("load start properties:" + propsFile.getAbsolutePath());
		Properties props = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(propsFile);
			if (fis != null) {
				props.load(fis);
			}
		} catch (Exception arg11) {
			throw new IllegalArgumentException(arg11);
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException arg10) {
					arg10.printStackTrace();
				}
			}
		}
		String bosentHome = props.getProperty("ofbiz.home");
		if(UtilValidate.isEmpty(bosentHome)) {
			throw new IllegalArgumentException("can\'t locate bosentHome,please make sure bosent.home entry existed in start.properties");
		} else {
			System.setProperty("ofbiz.home", bosentHome);
		}
	}
}
